﻿using System;
using System.Collections.Generic;
using System.Text;
using DialectSoftware.Networking;
using System.Linq;

namespace WebFabricator.org.Management
{
    public class SLSMPRequest
    {
        public SLSMPRequest(SLSMP method, string data)
        {
            TransactionID = Guid.NewGuid();
            Method = method;
            Data = data;
        }

        private SLSMPRequest(Guid transactionID)
        {
            TransactionID = transactionID;
        }

        public Guid TransactionID
        {
            get;
            private set;
        }

        public SLSMP Method
        {
            get;
            private set;
        }

        public String Data
        {
            get;
            private set;
        }

        public byte[] ToByteArray()
        {
            return System.Text.ASCIIEncoding.UTF8.GetBytes(String.Join("|", new[] { TransactionID.ToString(), Method.ToString(), Data ?? String.Empty }) + "^");
        }

        public static IEnumerable<SLSMPRequest> Parse(AsyncNetworkAdapter adapter)
        {
            string data = System.Text.ASCIIEncoding.UTF8.GetString(adapter.Buffer);
            var requets = data.Split('^');
            return requets
                .Where(r=>!String.IsNullOrEmpty(r))
                .Select(r =>
                {
                    int i = 0;
                    SLSMPRequest request = null;
                    r.Split('|')
                    .ForEach(s =>
                    {
                        switch (i)
                        {
                            case 0:
                                request = new SLSMPRequest(new Guid(s));
                                break;
                            case 1:
                                request.Method = (SLSMP)Enum.Parse(typeof(SLSMP), s);
                                break;
                            case 2:
                                switch (request.Method)
                                {
                                    case SLSMP.HELO:
                                        break;
                                    default:
                                        request.Data = s;
                                        break;
                                }
                                break;
                            default:
                                throw new NotSupportedException(data);
                        }
                        i++;
                    });
                return request;
            });
        }
    }
}
